
#include "base64.h"

//调用
void main() {

    //char *str = "0123456789abcdef0123456789abcdef";
    //char *buf = malloc(1024);
    //base64_encode(str, buf);
    //printf("%d:%s\r\n", strlen(buf), buf);

    char *buf = "MDEyMzQ1Njc4OWFiY2RlZg==";
    char *str = malloc(1024);
    base64_decode(buf, str);
    printf("%d:%s\r\n", strlen(str), str);
}
int base64_encode(char *str, char *buf) {


    BIO *bio_base64 = BIO_new(BIO_f_base64());
    BIO_set_flags(bio_base64, BIO_FLAGS_BASE64_NO_NL);
    BIO *bio_mem = BIO_new(BIO_s_mem());
    bio_mem = BIO_push(bio_base64, bio_mem);

    BIO_write(bio_mem, str, strlen(str));
    BIO_flush(bio_mem);
    BUF_MEM *buf_mem = NULL;
    BIO_get_mem_ptr(bio_mem, &buf_mem);
    buf = malloc(buf_mem->length + 1);
    memcpy(buf, buf_mem->data, buf_mem->length);
    buf[buf_mem->length] = '\0';
    BIO_free_all(bio_base64);
    printf("%d:%s\r\n", strlen(buf), buf);
    return 0;
}

int base64_decode(char *buf, char *str) {

    BIO *bio_base64 = BIO_new(BIO_f_base64());
    BIO_set_flags(bio_base64, BIO_FLAGS_BASE64_NO_NL);

    int len = strlen(buf);
    BIO *bio_mem = BIO_new_mem_buf(buf, len);
    bio_mem = BIO_push(bio_base64, bio_mem);
    str = malloc(sizeof(char) * (len + 1));
    int size = BIO_read(bio_mem, str, len);
    str[size] = '\0';
    BIO_free_all(bio_base64);
    printf("%d:%s\r\n", strlen(str), str);
    return 0;
}